<template>
  <div :class="'tinymce-box tinymce-editor-container ' + languageType">
    <!-- 编辑器主体 -->
    <editor
      ref="editorRef"
      v-model="editorValue"
      :init="init"
      @editor-click="onEditorClick"
      @show-composite-figure-dialog="onShowCompositeFigureDialog"
      @show-compare-dialog="onShowCompareDialog"
      @show-collaborate-dialog="onShowCollaborateDialog"
      @show-dept-dialog="onShowDeptDialog"
      @show-insert-dialog="onShowInsertDialog"
      @show-terms-mng-dialog="onShowTermsMngDialog"
      @show-terms-insert-dialog="onShowTermsInsertDialog"
      @show-docContent-insert-dialog="onShowDocContentInsertDialog"
      @close-docContent-insert-dialog="onCloseDocContentInsertDialog"
      @show-abbr-mng-dialog="onShowAbbrMngDialog"
      @show-abbr-insert-dialog="onShowAbbrInsertDialog"
      @show-reference-dialog="onShowReferenceDialog"
      @show-reference-mng-dialog="onShowRefMngDialog"
      @show-insert-variable="onShowInsertVariable"
      @show-variable-replace-dialog = "showVariableReplaceDialog"
      @show-material-dialog = "showMaterialDialog"
      @show-provision-dialog = "showProvisionDialog"
      @show-fastener-dialog = "showFastenerDialog"
      @show-loadCase-dialog = "showLoadCaseDialog"
      @show-relationFiles-dialog="showRelationFilesDialog"
    ></editor>

    <!-- 右侧侧边栏 -->
    <!-- 只有在编辑文档时有右侧侧边栏 -->
    <base-sidebar :sidebarItems="leftSidebarItems" :defaultActiveNav="'Outline'" side="left" />
    <audit-sidebar />
    <!-- 底部放大 -->
    <ZoomSlider class="zoomslider" />

    <CompositeFigureDialog ref="compositeFigureDialogRef" />
    <VersionsCompareDialog ref="compareDialogRef" />
    <CollaborateDialog ref="collaborateDialogRef" @show-user-dialog="onShowUserDialog" />
    <UserDialog ref="userDialogRef" />
    <DepartmentDialog ref="deptDialogRef" />
    <InsertDialog ref="insertDialogRef" />
    <!-- <ManageTermsDialog ref="termsMngDialogRef" /> -->
    <InsertTermsDialog ref="termsInsertDialogRef" />
    <ManageRefDialog ref="refMngDialogRef" />
    <ManageAbbrDialog ref="abbrMngDialogRef" />
    <InsertAbbrDialog ref="abbrInsertDialogRef" />
    <ReferenceDialog ref="referenceDialogRef" @show-content-dialog="onShowContentDialog" />
    <ContentDialog ref="contentDialogRef" />
    <DocContentDialog ref="docContentDialogRef" @show-content-dialog="onShowDocContentDialog" />
    <PageWrapper id="editorData" />
    <BlockList id="blockList" style="display: none" />
    <div id="termsTemplate" style="display: none">
      <TermGuideParagraph />
      <TermBlock v-for="item of $store.state.xmleditor.termBlockList" :key="item.blockId" :blockData="item" />
    </div>
    <AbbrTableTemplate id="abbrTemplate" />
    <!-- 添加变量 -->
    <VariableDialog ref="referenceVariableRef"/>
    <VariableRepalceDialog ref="referenceVariableReplaceRef"/>
    <MaterialDialog ref="referenceMaterialDialogRef"/>
    <ProvisionReplaceDialog ref="referencProvisionDialogRef"/>
    <FastenerDialog ref="referencFastenerDialogRef"/>
    <LoadCaseDialog ref="referencLoadCaseDialogRef" />
    <RelationFilesDialog ref="referencRelationFilesDialogRef" />
  </div>
</template>

<script>
import Vue from 'vue'
import { mapGetters } from 'vuex'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/skins/content/default/content.css'
import 'tinymce/themes/silver/theme.min.js'
import 'tinymce/icons/default/icons'
import '@/utils/plugins/image'
import '@/utils/plugins/charmap' // 特殊字符
import '@/utils/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/link'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/noneditable'
import '../../../public/tinymce/plugins/kityformula'
import '@/utils/plugins'
import BaseSidebar from './__components__/BaseSidebar.vue'
import AuditSidebar from './__components__/AuditSidebar.vue'
import ZoomSlider from './__components__/ZoomSlider.vue'
import CompositeFigureDialog from './__components__/dialogs/CompositeFigureDialog.vue'
import VersionsCompareDialog from './__components__/dialogs/VersionsCompareDialog.vue'
import CollaborateDialog from './__components__/dialogs/CollaborateDialog.vue'
import UserDialog from './__components__/dialogs/UserDialog.vue'
import DepartmentDialog from './__components__/dialogs/DepartmentDialog.vue'
import InsertDialog from './__components__/dialogs/InsertDialog.vue'
import TermGuideParagraph from './__components__/blocks/TermGuideParagraph.vue'
import InsertTermsDialog from './__components__/dialogs/InsertTermsDialog.vue'
import ManageRefDialog from './__components__/dialogs/ManageRefDialog.vue'
import ManageAbbrDialog from './__components__/dialogs/ManageAbbrDialog.vue'
import InsertAbbrDialog from './__components__/dialogs/InsertAbbrDialog.vue'
import ReferenceDialog from './__components__/dialogs/ReferenceDialog.vue'
import ContentDialog from './__components__/dialogs/ContentDialog.vue'
import DocContentDialog from './__components__/dialogs/DocContentDialog.vue'
import PageWrapper from './__components__/PageWrapper.vue'
import BlockList from './__components__/blocks/BlockList.vue'
import { init_instance_callback, images_upload_handler, setup } from '@/utils/init'
import { getEditorParams } from '@/utils/helpers'
import TermBlock from './__components__/blocks/TermBlock.vue'
import AbbrTableTemplate from './__components__/blocks/AbbrTableTemplate.vue'
import VariableDialog from './__components__/dialogs/VariableDialog.vue'
import VariableRepalceDialog from './__components__/dialogs/VariableRepalceDialog.vue'
import ProvisionReplaceDialog from './__components__/dialogs/ProvisionReplaceDialog.vue'
import MaterialDialog from './__components__/dialogs/MaterialDialog.vue'
import FastenerDialog from './__components__/dialogs/FastenerDialog.vue'
import LoadCaseDialog from './__components__/dialogs/LoadCaseDialog.vue'
import RelationFilesDialog from './__components__/dialogs/RelationFilesDialog.vue'
import { Message } from 'element-ui'
export default {
  props: {
    docNo: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    userNo: {
      type: String,
      default: ''
    },
    entry: {
      type: String,
      default: '' // 1. 无，2. flow, 3. preview
    },
    keyword: {
      type: String,
      default: '' // 全文搜索，关键字高亮
    },
    collaborate: {
      type: Boolean,
      default: false
    },
    editContentType: {
      type: String,
      default: 'document' // document | template | block | collect
    }
  },
  components: {
    ZoomSlider,
    PageWrapper,
    BaseSidebar,
    AuditSidebar,
    CompositeFigureDialog,
    CollaborateDialog,
    UserDialog,
    DepartmentDialog,
    InsertDialog,
    TermGuideParagraph,
    InsertTermsDialog,
    ManageRefDialog,
    ManageAbbrDialog,
    InsertAbbrDialog,
    ReferenceDialog,
    ContentDialog,
    DocContentDialog,
    VersionsCompareDialog,
    BlockList,
    TermBlock,
    AbbrTableTemplate,
    Editor,
    VariableDialog,
    VariableRepalceDialog,
    ProvisionReplaceDialog,
    MaterialDialog,
    FastenerDialog,
    LoadCaseDialog,
    RelationFilesDialog
  },
  name: 'xml-editor',
  data() {
    tinymce.baseURL = ''
    const { plugins, toolbar, menu } = getEditorParams.apply(this)
    const baseCssURL = `/tinymce/skins/content/default`
    const editContentType = this.$route.query.editContentType || this.editContentType
    return {
      init: {
        language_url: tinymce.baseURL + `/tinymce/langs/zh_CN.js`,
        language: 'zh_CN',
        skin_url: `/tinymce/skins/ui/oxide`,
        convert_urls: true,
        height: '100%',
        content_css: [baseCssURL + `/content.css`, baseCssURL + `/custom.css`],
        plugins,
        toolbar,
        formats: {
          bizIndex: {
            inline: 'span',
            attributes: {
              'data-type': 'bizIndex',
              'data-id': '%dataId',
              'data-content': '%content',
              'data-content-number': '%contentNumber'
            }
          },
          keyword: {
            inline: 'span',
            attributes: { 'data-type': 'keyword', title: '%title', 'data-content': '%title', 'data-id': '%dataId' }
          },
          // 警告：虽然以下写法是官方文档推荐，但是存在编写异常，不要使用
          subscript: { inline: 'sub', attributes: { 'data-type': 'sub' } },
          superscript: { inline: 'sup', attributes: { 'data-type': 'sup' } }
        },
        elementpath: false,
        statusbar: false,
        menubar: 'file reference insert tools',
        extended_valid_elements: 'span[class|style]',
        // valid_elements: 'span[class|style],p[class|style]',
        menu,
        setup, // 阻止默认事件
        branding: false,
        noneditable_noneditable_class: 'noneditable',
        contextmenu_never_use_native: true,
        contextmenu: 'pageContextmenu paraLang table',
        images_upload_handler,
        object_resizing: 'img,table:not(.unresizable):not([contenteditable="false"])', // 哪些元素可以调整尺寸
        fullscreen_native: true, // 使用浏览器原生的全屏功能
        init_instance_callback // 初始化实例后
      },
      editorValue: `<div id="editorApp"></div>`
    }
  },
  computed: {
    _id() {
      return this.$store.state.xmleditor._id
    },
    ...mapGetters(['leftSidebarItems', 'languageType'])
  },
  mounted() {
    this.$store.commit('xmleditor/SET_EDITOR_REF', this.$refs.editorRef)
    window.getSelectedBlocks = () => tinymce.activeEditor.dom.select('label[data-iframe-checkbox].is-checked')

    // 水印会超出页面高度
    const body = document.querySelector('body')
    body.style.overflow = 'hidden'
  },
  beforeDestroy() {
    const body = document.querySelector('body')
    body.style.overflow = 'auto'
  },
  methods: {
    onEditorClick() {
      window.dispatchEvent(new Event('innerEditorClick'))
    },
    onShowCompositeFigureDialog() {
      this.$refs.compositeFigureDialogRef.show()
    },
    onShowCompareDialog() {
      this.$refs.compareDialogRef.show()
    },
    onShowCollaborateDialog() {
      this.$refs.collaborateDialogRef.show()
    },
    onShowUserDialog() {
      this.$refs.userDialogRef.show()
    },
    onShowDeptDialog() {
      this.$refs.deptDialogRef.show()
    },
    onShowInsertDialog() {
      this.$refs.insertDialogRef.show()
    },
    onShowTermsMngDialog() {
      this.$refs.termsMngDialogRef.show()
    },
    onShowTermsInsertDialog() {
      this.$refs.termsInsertDialogRef.show()
    },
    onShowDocContentInsertDialog() {
      this.$refs.docContentDialogRef.show()
    },
    onCloseDocContentInsertDialog() {
      this.$refs.docContentDialogRef.handleClose()
    },
    onShowRefMngDialog() {
      this.$refs.refMngDialogRef.show()
    },
    onShowAbbrMngDialog() {
      this.$refs.abbrMngDialogRef.show()
    },
    onShowAbbrInsertDialog() {
      this.$refs.abbrInsertDialogRef.show()
    },
    onShowContentDialog() {
      this.$refs.contentDialogRef.show()
    },
    onShowDocContentDialog() {
      this.$refs.contentDialogRef.show('doc')
    },
    onShowReferenceDialog() {
      this.$refs.referenceDialogRef.show()
    },
    //添加变量
    onShowInsertVariable(){
       // 文章编辑时不允许插入变量
      // if(this.$store.state.xmleditor.editorConfig.editContentType ==='template'){
        this.$refs.referenceVariableRef.show()
      // }else{
      //   Message.warning('文档编辑时不允许插入变量！')
      // }
    },
    showVariableReplaceDialog(){
      this.$refs.referenceVariableReplaceRef.show()
    },
    //材料选择
    showMaterialDialog(){
      this.$refs.referenceMaterialDialogRef.show()
    },
    //条款库
    showProvisionDialog(){
      this.$refs.referencProvisionDialogRef.show()
    },
    //紧固件
    showFastenerDialog(){
      this.$refs.referencFastenerDialogRef.show()
    },
    //工况
    showLoadCaseDialog(){
      this.$refs.referencLoadCaseDialogRef.show()
    },
    // 依据性文件
    showRelationFilesDialog(){
      this.$refs.referencRelationFilesDialogRef.show()
    }
  },
  watch: {
    _id() {
      new Vue({ render: h => h(PageWrapper) }).$mount(tinymce.activeEditor.dom.select('#editorApp')[0])
    },
    editorValue(newValue) {
      this.$emit('input', newValue)
    }
  },
  created() {
    const query = this.$route.query
    const payload = {
      id: this.id || query.id,
      docNo: this.docNo || query.docNo,
      userNo: this.userNo || query.userNo,
      entry: this.entry || query.entry || '',
      keyword: this.keyword || query.keyword || '',
      collaborate: this.collaborate || query.collaborate === 'true' || query.collaborate === true,
      validToken: query.validToken || '',
      _iframe: query._iframe,
      editContentType: query.editContentType || this.editContentType || 'document'
    }
    this.$store.commit('xmleditor/INIT_EDITOR_CONFIG', payload)
    this.$store.commit('xmleditor/INIT_ORIGINAL_EDITOR_CONFIG', payload)
  }
}
</script>
<style>
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.tox-tinymce.htmlpreview .slot-component .content {
  border-left: 1px solid #ccc;
}

.tox-tinymce.htmlpreview .tox-menubar,
.tox-tinymce.htmlpreview .slot-component ul.nav,
.tox-tinymce.htmlpreview .slot-component .collapse,
.tox-tinymce.htmlpreview .wrapper.zoomslider {
  display: none;
}

#app,
.tinymce-editor-container {
  height: 100%;
}

.tinymce-editor-container .tox-tinymce {
  height: 100%;
  border: none;
}

/* 工具栏样式居中显示 */
.tox .tox-toolbar-overlord {
  text-align: center;
  border-bottom: 1px solid #ccc;
}

.tox .tox-editor-header .tox-toolbar-overlord {
  height: 48px;
}

.tox .tox-editor-header button.tox-tbtn {
  flex-wrap: wrap;
  height: 41px;
  min-width: 45px;
  max-width: 52px;
  font-size: 10px;
  position: relative;
  margin: 2px 0;
  padding: 0;
}

.tox .tox-editor-header button.tox-tbtn span {
  display: inline-block;
  text-align: center;
  width: 40px;
}

.tox .tox-editor-header button.tox-tbtn svg {
  display: inline-block;
  width: 24px;
  height: 24px;
}

.tox .tox-editor-header .tox-tbtn::after {
  content: attr(title);
  display: inherit;
}
.tox .tox-editor-header .tox-tbtn__select-chevron {
  position: absolute;
  left: 40px;
  top: 10px;
}

.tox .tox-toolbar-overlord.tox-tbtn--disabled {
  background: 0 0;
  border: 0;
  box-shadow: none;
  color: rgba(34, 47, 62, 0.5);
}

.tox .tox-toolbar-overlord.tox-tbtn--disabled,
.tox .tox-toolbar-overlord.tox-tbtn--disabled:hover {
  background: inherit;
  border-bottom: 1px solid #ccc;
  height: 0;
}

.tox .tox-menubar + .tox-toolbar,
.tox .tox-menubar + .tox-toolbar-overlord .tox-toolbar__primary {
  display: inline-block;
  border-bottom: none;
  margin-top: 0;
  background: none;
}

.tox .tox-editor-header .tox-menubar {
  background-color: #025da4;
}
.tox .tox-editor-header .tox-mbtn {
  color: #fff;
}

.tox-menubar[role='menubar'] img {
  width: 32px;
  height: 23px;
  margin: 7px 20px 3px 15px;
}
.tox .tox-collection--list div.tox-collection__group {
  padding: 0;
}
</style>
